<template>
  <div class="nav">
    <div v-if="qwe">
      <div class="box">
        <div class="box-sm">
          <span class="size">客户姓名</span>
          <el-input v-model="dataarr.name" size="small" style="width: 150px" placeholder="请输入客户姓名" />
        </div>
        <div class="box-sm">
          <span class="size">客户手机</span>
          <el-input
            v-model="dataarr.phone"
            size="small"
            style="width: 150px"
            placeholder="请输入客户姓名"
          />
        </div>
        <div class="box-sm">
          <span class="size">归属人</span>
          <el-input
            v-model="dataarr.owner"
            size="small"
            style="width: 150px"
            placeholder="请输入客户姓名"
          />
        </div>
        <div class="box-sm">
          <span class="size">渠道来源</span>
          <el-select
            size="small"
            style="width: 150px"
            v-model="dataarr.channelId"
            placeholder="渠道来源"
          >
            <el-option
              v-for="(item ,index) in channelsarr"
              :key="index"
              :label="item.channelName"
              :value="item.channelId"
            />
          </el-select>
        </div>
      </div>
      <div class="box" style="margin-top: 20px;">
        <div class="box-sm">
          <span class="size">线索状态</span>
          <el-select size="small" style="width: 150px" v-model="dataarr.status" placeholder="渠道来源">
            <el-option
              v-for="(item ,index) in statusdata"
              :key="index"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </div>
        <div class="box-sm" style="display: flex;">
          <span class="size">跟进时间</span>
          <div class="demo-datetime-picker">
            <div class="block">
              <el-date-picker
                width="350"
                size="small"
                v-model="timeaddup"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="YYYY/MM/DD ddd"
                time-format="A hh:mm:ss"
              />
            </div>
          </div>
          <div style=" padding-left:25px ">
            <el-button size="small" type="primary" @click="search" :icon="Search">搜索</el-button>
          </div>
          <div style=" padding-left:15px ">
            <el-button size="small" type="Search" :icon="Refresh" @click="reset">重置</el-button>
          </div>
        </div>
      </div>
    </div>
    <div style="">
      <el-button size="small" type="primary" plain :icon="Plus" @click="addition">新增</el-button>
      <el-button
        size="small"
        type="success"
        plain
        :icon="Edit"
        v-if="getinfo.length==1"
        @click="putdata"
      >修改</el-button>
      <el-button size="small" type="success" plain :icon="Edit" v-else disabled>修改</el-button>
      <el-button
        size="small"
        type="danger"
        plain
        :icon="Delete"
        v-if="getinfo.length>0"
        @click="deledata"
      >删除</el-button>
      <el-button size="small" type="danger" plain :icon="Delete" v-else disabled>删除</el-button>
      <el-button size="small" type="warning" plain :icon="Download" @click="add">导出</el-button>
      <div style="float: right;display: flex;">
        <div
          style="border: 1px solid #999;display: flex;width: 30px;height: 30px;justify-content: space-around; align-items: center;border-radius: 50%;" @click="ad"
        >
          <el-icon>
            <Search />
          </el-icon>
        </div>
        <div
          style="border: 1px solid #999;display: flex;width: 30px;height: 30px;justify-content: space-around; align-items: center;border-radius: 50%;margin:0 0 0 20px"
          @click="asdasd"
        >
          <el-icon>
            <Refresh />
          </el-icon>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div style="margin-top: 10px;">
      <el-table
        ref="multipleTableRef"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :row-key="getRowKeys"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="线索编号">
          <template #default="scope">{{ scope.row.clueId }}</template>
        </el-table-column>
        <el-table-column property="name" label="客户姓名" />
        <el-table-column property="phone" label="手机号码" />
        <el-table-column property="channelName" label="渠道来源" />
        <el-table-column property="createTime" width="200" label="创建时间" />
        <el-table-column property="owner" label="线索归属" />
        <el-table-column label="线索状态">
          <template #default="scope">
            <div class="buttbox" v-for="(item , index) in statusdata" :key="index">
              <!-- <span :class="item.listClass" :type="item.dictType" v-if="scope.row.status==item.dictValue">{{ item.dictLabel }}</span> -->
              <el-button
                :class="item.dictType"
                :type="item.listClass"
                v-if="scope.row.status==item.dictValue"
                plain
              >{{ item.dictLabel }}</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="nextTime" width="200" label="下超跟进时间" />
        <el-table-column property="操作" width="160" label="操作">
          <template #default="scope">
            <div class="coazbuttonm">
              <el-button type="primary" size="small" :icon="Search" @click="examine(scope.row)">查看</el-button>
              <el-button
                v-if="scope.row.status!=2"
                type="primary"
                size="small"
                :icon="Pointer"
                @click="distribution(scope.row)"
              >分配</el-button>

              <el-button
                v-if="scope.row.owner=='admin'"
                type="primary"
                size="small"
                :icon="TopRight"
                @click="examineup(scope.row)"
              >跟进</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div style="margin-top: 20px">
      <el-button
        @click="toggleSelection([tableData[1], tableData[2]])"
      >Toggle selection status of second and third rows</el-button>
      <el-button @click="toggleSelection()">Clear selection</el-button>
    </div>-->
    <!-- 分页器 -->
    <div
      style="display: flex;flex-direction: row;justify-content: flex-end;padding:20px 20px 0px 20px"
    >
      <el-pagination
        v-model:current-page="currentPage4"
        v-model:page-size="pageSize4"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Inall"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增模态框 -->
    <el-dialog v-model="dialogFormVisible" :title="id==1?'修改线索':'添加线索'" width="500">
      <el-form
        :model="ruleForm"
        ref="ruleFormRef"
        style="max-width: 600px"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <div style="display: flex;">
          <el-form-item label="手机号码" placeholder="请输入手机号码" prop="phone">
            <el-input size="small" v-model="ruleForm.phone" />
          </el-form-item>
          <el-form-item label="客户姓名" placeholder="请输入客户姓名" prop="name">
            <el-input size="small" v-model="ruleForm.name" />
          </el-form-item>
        </div>
        <div style="display: flex;">
          <el-form-item label="渠道来源">
            <el-select size="small" style="width: 150px" v-model="gongz" placeholder="渠道来源">
              <el-option
                v-for="(item ,index) in channelsarr"
                :key="index"
                :label="item.channelName"
                :value="item.channelId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="活动信息">
            <el-select
              size="small"
              style="width: 150px"
              v-model="ruleForm.activityId"
              placeholder="活动状态"
            >
              <el-option
                v-for="(item , index) in activityarr"
                :key="index"
                :label="item.name"
                :value="item.activityId"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="display: flex;">
          <el-form-item label="客户性别" placeholder="请输入手机号码" style="width: 228px;">
            <el-radio-group size="small" v-model="ruleForm.gender" class="ml-4">
              <el-radio :label="1" width="30" size="small">男</el-radio>
              <el-radio :label="2" size="small">女</el-radio>
              <el-radio :label="3" size="small">未知</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="客户年龄" placeholder="年龄" style="width: 228px;">
            <el-input-number
              v-model="ruleForm.age"
              placeholder="年龄"
              :min="6"
              @change="handleChange"
            />
          </el-form-item>
        </div>
        <div style="display: flex;">
          <el-form-item label="微信号" placeholder="请输入微信号码">
            <el-input size="small" v-model="ruleForm.weixin" />
          </el-form-item>
          <el-form-item label="QQ号码" placeholder="请输入QQ号码">
            <el-input size="small" v-model="ruleForm.qq" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配线索 -->
    <el-dialog v-model="dialogFormVisiblexin" :title="id==1?'修改线索':'添加线索'">
      <el-form
        :model="ruleForm2"
        ref="ruleFormRef2"
        :rules="rules2"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <div style="display: flex;">
          <el-form-item label="归属部门">
            <el-tree-select
              v-model="treeselect"
              :data="treeselectdata"
              check-strictly
              :render-after-expand="false"
              style="width: 240px"
              placeholder="请选择归属部门"
            />
          </el-form-item>

          <el-form-item label="分配给">
            <el-select style="width: 240px" v-model="Share" placeholder="活动状态">
              <el-option
                v-for="(item , index) in Sharearr"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="subit">确定</el-button>
          <el-button @click="dialogFormVisiblexin.value=false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive,watch } from "vue";
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
const id=ref("0")
//导出
// import { aoaToSheetXlsx } from '@/utils/ExportExcel'

/**声明 */
const add=()=>{
    console.log(99999999)
    let header = [   //表头
    {label:'手机号', prop:'name' }, 
    {label:'类型', prop:'type' },
    {label:'状态', prop:'status' }
  ]
  const data=reactive([		//导出的数据
    
  ])
  data.value=tableData.value
//   console.log(data.value)
  aoaToSheetXlsx({
    header,
    data: data.value,
    filename: 'excel导出名字',   //excel文件名
  })
}

import { ElMessage, ElTable ,ElMessageBox} from "element-plus";
import { cluelist,cluestatus,channels,activity,cluesubmit,summary,delectdara,PUTsubmit,Cueallocation,Sharedata,assignment} from "@/api/tienchin/xiansuoguanli";
import {
  Search,
  Refresh,
  Plus,
  Edit,
  View,
  Delete,
  Download,
  TopRight,
  Pointer
} from "@element-plus/icons-vue";

const input = ref("");
const fromdata = ref({
  value: 0,
});

//渠道来源
const channelsarr=ref([])
const channelsdata=()=>{
    channels().then(res => {
    
    if (res.code != 200) return ElMessage.error("查询用户列表失败");
    channelsarr.value=res.data
    console.log(channelsarr.value);
  });
}
//模态框
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
// const formSize = ref<ComponentSize>('default')
// const ruleFormRef = ref<FormInstance>()
//     const locationOptions = ['Home', 'Company', 'School']
const ruleForm = ref({
  name: "",
  phone:"",
  gender:0,
  age:"",
  qq:"",
  channelId:"",
  weixin:"",
  activityId:''
});
const handleChange = (value: number) => {
  console.log(value)
}
const radio2 = ref('1')
const radio = ref(3)
const dialogFormVisible = ref(false);
const dialogFormVisiblexin = ref(false);
const rules = reactive<FormRules<RuleForm>>({
    phone: [
    { required: true, message: "手机号码不能为空", trigger: "blur" }
  ],
  name: [
    { required: true, message: "客户姓名不能为空", trigger: "blur" }
  ]
});

//提交模态框
const submit=()=>{
    
  if(id.value==0){
    cluesubmit(ruleForm.value).then(res => {
    console.log(res);
    if (res.code != 200) return ElMessage.error("查询用户列表失败");
    ElMessage.success("新增成功");
  });
  }else{
    PUTsubmit(ruleForm.value).then(res => {
    console.log(res);
    if (res.code != 200) return ElMessage.error("查询用户列表失败");
    ElMessage.success("修改成功");
  });
  }
  dialogFormVisible.value = false
  ruleForm.value={ name: "",
  phone:"",
  gender:0,
  age:"",
  qq:"",
  channelId:"",
  weixin:"",
  activityId:''}
 console.log(ruleForm.value)
}
//活动信息
const gongz=ref('')
const activityarr=ref([])
watch(gongz, (newValue, oldValue) => {
      console.log(newValue);
      activity(newValue).then(res => {
    console.log(res);
    if (res.code != 200) return ElMessage.error("查询用户列表失败");
    activityarr.value=res.data
    ruleForm.value.channelId=newValue
 
  });
    });

//线索状态数据
const statusdata=ref([])
const cluestatusdata=()=>{
    cluestatus().then(res => {
    console.log(res);
    if (res.code != 200) return ElMessage.error("查询用户列表失败");
    statusdata.value=res.data
  });
}
//分页器
const currentPage4 = ref(1);
const pageSize4 = ref(10);
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  queryInfo.value.pageSize = val;
  cluelistdata();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  queryInfo.value.pageNum = val;
  cluelistdata();
};
//表格
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<User[]>([]);
const toggleSelection = (rows?: User[]) => {
  if (rows) {
    rows.forEach(row => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value!.toggleRowSelection(row, undefined);
    });
  } else {
    multipleTableRef.value!.clearSelection();
  }
};
const getinfo=ref([])
const handleSelectionChange = (val: User[]) => {
//   multipleSelection.value = val;
// multipleSelection.value.push(val)
//   console.log(multipleSelection.value)
getinfo.value=val
  console.log(getinfo.value)
};
const putdata=()=>{
  id.value=1
  console.log(getinfo.value[0].clueId)
  summary(getinfo.value[0].clueId).then(res => {
    console.log(res);
    if (res.code != 200) return ElMessage.error("查询用户列表失败");
    ruleForm.value=res.data
    gongz.value=res.data.channelId
  });

    dialogFormVisible.value = true
    
    // ruleForm.value=getinfo.value[0]
    // console.log(ruleForm.value)
}
const tableData = ref([]);
const getRowKeys = (row) => {
      //记录每行的key值
      return row.id;
    }
//跟进时间选择
const value1 = ref("");
const value2 = ref("");
//查询数据

const queryInfo = ref({
  pageNum: 1,
  pageSize: 10,
  params:{}
});
//数据总个数
const Inall = ref("");
const cluelistdata = () => {
  console.log(999);
  cluelist(queryInfo.value).then(res => {
    console.log(res);
    Inall.value = res.total;
    if (res.code != 200) return ElMessage.error("查询用户列表失败");
    tableData.value = res.rows;

    for(let i=0;i<tableData.value.length;i++){
        let time=tableData.value[i].createTime.split("T")
        let time2=tableData.value[i].nextTime.split("T")
      tableData.value[i].createTime=time[0]+" "+time[1]
      tableData.value[i].nextTime=time2[0]+" "+time[1]
    }
  });
}

//搜索
const dataarr=ref({
    status:"",
    channelId:"",
    owner:"",
    phone:"",
    name:"",
    pageNum: 1,
    pageSize: 10
})
const dateRange=ref([])
import { formData } from "@/components/format";
const timeaddup=ref("")
const search=()=>{
   if(dataarr.value.name!=""){
    queryInfo.value.name=dataarr.value.name
   }
   if(dataarr.value.status!=""){
    queryInfo.value.status=dataarr.value.status
   }
   if(dataarr.value.channelId!=""){
    queryInfo.value.channelId=dataarr.value.channelId
   }
   if(dataarr.value.owner!=""){
    queryInfo.value.owner=dataarr.value.owner
   }
   if(dataarr.value.phone!=""){
    queryInfo.value.phone=dataarr.value.phone
   }
   if(timeaddup.value!=""){
    timeaddup.value[0] = formData.formDate(timeaddup.value[0]);
   timeaddup.value[1] = formData.formDate(timeaddup.value[1]);
   queryInfo.value.dateRange=[formData.formDate(timeaddup.value[0]),formData.formDate(timeaddup.value[1])]
queryInfo.value.params.beginTime = timeaddup.value[0];
queryInfo.value.params.endTime = timeaddup.value[1];
   }


   console.log(timeaddup.value)
   cluelist(queryInfo.value).then(res => {
    console.log(res);
    Inall.value = res.total;
    if (res.code != 200) return ElMessage.error("查询用户列表失败");
    tableData.value = res.rows;
    for(let i=0;i<tableData.value.length;i++){
        let time=tableData.value[i].createTime.split("T")
        let time2=tableData.value[i].nextTime.split("T")
      tableData.value[i].createTime=time[0]+" "+time[1]
      tableData.value[i].nextTime=time2[0]+" "+time[1]
    }
  });
    console.log(queryInfo.value)
    queryInfo.value={ pageNum: 1,pageSize: 10,params:{}}
}
//删除数据
const deledata=()=>{
  // console.log(getinfo.value[0])

  const datasubit=ref([])
  // datasubit.value=getinfo.value[0]
  // console.log(datasubit.value)
  const daelect=ref([])
  for(let i=0;i<getinfo.value.length;i++){
    datasubit.value.push(getinfo.value[i].clueId)
  }

  ElMessageBox.confirm(
    `是否确认删除线索编号为"${datasubit.value}"的数据项?`,
    '系统提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      console.log(datasubit.value)
  delectdara(datasubit.value).then(res=>{
    if (res.code != 200) return ElMessage.error("删除失败");
  
    cluelistdata()
  })
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'success',
        message: '删除失败',
      })
    })
}
//重置
const reset=()=>{
  timeaddup.value=""
  dataarr.value={
    status:"",
    channelId:"",
    owner:"",
    phone:"",
    name:"",
    pageNum: 1,
    pageSize: 10
}
}
//归属部门
const treeselect=ref("")
const treeselectdata=ref()

const addition=()=>{
  id.value=0
  gongz.value=''
  ruleForm.value={
  name: "",
  phone:"",
  gender:0,
  age:"",
  qq:"",
  channelId:"",
  weixin:"",
  activityId:''
}
  dialogFormVisible.value=true
}
//分配线索模块
const datadate=ref({
  assignId:'',
  departmentId:'',
  deptId:'',
  nickName:'',
  type:0,
  userId:'',
  userName:''
})
const distribution=(row)=>{
  Cueallocation().then(res => {

    if (res.code != 200) return ElMessage.error("查询用户列表失败");
    treeselectdata.value=res.data
    
    treeselectdata.value=JSON.parse(JSON.stringify(treeselectdata.value).replace(/id/g,"value").replace(/colName/g,"label"))
  });
  console.log(555)
    console.log(row);
    datadate.value.assignId=row.clueId
  dialogFormVisiblexin.value=true
}
const arr=ref('')
const subit=()=>{
  // console.log(treeselect.value)
  // console.log(Share.value)
  for(let i=0;i<Sharearr.value.length;i++){
    if(Sharearr.value[i].value==Share.value){
      arr.value=Sharearr.value[i]
    }
  }
 
  datadate.value.deptId=arr.value.value
  datadate.value.userName=arr.value.userName
  datadate.value.nickName=arr.value.label
  datadate.value.userId=arr.value.userId
  // console.log(arr.value)
  console.log(datadate.value)
  assignment(datadate.value).then(res=>{
    console.log(res);
        if (res.code != 200) return ElMessage.error("查询用户列表失败");
        datadate.value={
          assignId:'',
          departmentId:'',
          deptId:'',
          nickName:'',
          type:0,
          userId:'',
          userName:''
        } 
        dialogFormVisiblexin.value=false
        cluelistdata();
  })
}
const Share=ref("")
const Sharearr=ref("")
watch(treeselect, (newValue, oldValue) => {
      console.log(newValue);
      Sharedata(newValue).then(res => {
        console.log(res);
        if (res.code != 200) return ElMessage.error("查询用户列表失败");
        Sharearr.value=JSON.parse(JSON.stringify(res.data).replace(/deptId/g,"value").replace(/nickName/g,"label"))
        console.log(Sharearr.value)
        datadate.value.departmentId=newValue
      });
    });
    watch(Share, (newValue, oldValue) => {
      console.log(newValue);
      
    });
    import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();
const examine=(row)=>{
  console.log(row)
  router.push("/clue/details/index/" + row.clueId + "/view");
}
const examineup=(row)=>{
  console.log(row)
  router.push("/clue/details/index/" + row.clueId + "/follow");
}
const qwe=ref(true)
const ad=()=>{
  console.log(66)
  qwe.value=!qwe.value
}
const asdasd=()=>{
  cluelistdata();
}
onMounted(() => {
  cluelistdata();
  cluestatusdata();
  channelsdata()
});
</script>

<style lang="scss" scoped>
.coazbuttonm {
  .el-button {
    background-color: rgba(0, 0, 0, 0);
    color: #409eff;
    border: 0;
  }
  .el-button:hover {
    background-color: #f5f7fa;
  }
}
.buttbox {
  .el-button {
    pointer-events: none;
    // color:#409eff;
    // border-color:#9fceff;
    // background-color:#ebf5ff
  }
}
//单选框
.el-radio.el-radio--small {
  margin-right: 10px;
}
.el-form-item__content {
  width: 150px;
}
// 分页器
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
// 跟进时间样式
.demo-datetime-picker {
  display: flex;
  padding: 0;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: stretch;
}
.demo-datetime-picker .block {
  padding: 30px 0;
  text-align: center;
}
.line {
  width: 1px;
  background-color: var(--el-border-color);
}
.nav {
  padding: 20px;
  .box {
    display: flex;

    .box-sm {
      margin-right: 60px;
      .size {
        font-size: 14px;
        font-weight: 800;
        margin-right: 15px;
      }
    }
  }
}
.block {
  padding: 0 !important;
}
</style>